﻿using Grow.Domain.EventBus.Cap.SubscriberDomainEvents;
using Grow.Domain.EventBus.CreateDomainEventBus;
using Grow.Module.Options;
using Grow.Module.Service;
using Microsoft.Extensions.DependencyInjection;

namespace Grow.Domain.EventBus.Cap.Kafka.CreateDomainEventBus
{
    public class CreateDomainEventBusBuilder : ICreateDomainEventBusBuilder
    {
        private readonly IServiceContainer _serviceContainer;

        public CreateDomainEventBusBuilder(IServiceContainer serviceContainer)
        {
            _serviceContainer = serviceContainer;
        }
        public ICreateDomainEventBusBuilder AddDomainEventBus(Action<IOptionsBind, DomainEventBusOptions> domainEventBusOptionsAction)
        {
            _serviceContainer.OptionsManager.AddOptions<DomainEventBusOptions>(a =>
            {
                domainEventBusOptionsAction(_serviceContainer.OptionsManager.GetOptionsBind(), a);
            });
            return this;
        }
        public ICreateDomainEventBusBuilder AddDomainEvent<TDomainEvent>(Action<IOptionsBind, DomainEventOptions> domainEventOptionsAction) where TDomainEvent : IDomainEvent
        {
            _serviceContainer.OptionsManager.AddOptions<DomainEventOptions>(typeof(TDomainEvent).FullName!, a =>
            {
                domainEventOptionsAction(_serviceContainer.OptionsManager.GetOptionsBind(), a);
            });
            return this;
        }

        public ICreateDomainEventBusBuilder AddDomainEventHandler<TDomainEventHandler, TDomainEvent>(Action<IOptionsBind, DomainEventHandlerOptions> domainEventHandlerOptionsAction)
            where TDomainEventHandler : class, IDomainEventHandler<TDomainEvent>
            where TDomainEvent : IDomainEvent
        {
            _serviceContainer.OptionsManager.AddOptions<DomainEventHandlerOptions>(typeof(TDomainEventHandler).FullName!, a =>
            {
                domainEventHandlerOptionsAction(_serviceContainer.OptionsManager.GetOptionsBind(), a);
            });

            _ = _serviceContainer.ServiceCollection.AddTransient<TDomainEventHandler>();
            _ = _serviceContainer.ServiceCollection.AddSingleton<ISubscriberDomainEvent, SubscriberDomainEvent<TDomainEventHandler, TDomainEvent>>();
            return this;
        }


    }
}
